// ==UserScript==
// @name         音频版
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  自动填充YouTube视频的多语言标题（适配新版界面）
// @author       行走的Penny
// @match        https://studio.youtube.com/video/*/translations
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';
    // CSS with more targeted selectors
    const customStyles = `
        /* Target only the specific hover elements we need */
        ytgn-video-translation-hover-cell.show-buttons,
        .metadata-hover-cell-container ytgn-video-translation-hover-cell.show-buttons {
            opacity: 1 !important;
            visibility: visible !important;
        }

        /* Make buttons inside marked containers visible */
        ytgn-video-translation-hover-cell.show-buttons button,
        .metadata-hover-cell-container .show-buttons button {
            opacity: 1 !important;
            visibility: visible !important;
            display: inline-block !important;
            pointer-events: auto !important;
        }
    `;

    // Add our custom CSS
    function addCustomStyles() {
        const styleEl = document.createElement('style');
        styleEl.id = 'yt-translation-buttons-smart';
        styleEl.textContent = customStyles;
        document.head.appendChild(styleEl);
        console.log('YouTube Translation Buttons: Added smart custom styles');
    }

    // Process hover cells with condition check
    function processHoverCells() {
        // Target the translation containers
        const containers = document.querySelectorAll('ytgn-video-translation-hover-cell, .metadata-hover-cell-container');

        if (containers.length) {
            console.log(`Found ${containers.length} translation containers`);

            containers.forEach(container => {
                // Check if status is "–" before proceeding
                const statusElement = container.querySelector('#status-info');
                if (statusElement && statusElement.textContent.trim() === '–') {
                    //console.log('Found a container with "–" status, showing buttons');

                    // Mark this container for CSS targeting
                    container.classList.add('show-buttons');

                    // Trigger hover event
                    ['mouseenter', 'mouseover'].forEach(eventType => {
                        const event = new MouseEvent(eventType, {
                            bubbles: true,
                            cancelable: true,
                            view: window
                        });
                        container.dispatchEvent(event);
                    });

                    // Make buttons visible
                    const buttons = container.querySelectorAll('button');
                    buttons.forEach(btn => {
                        btn.style.visibility = 'visible';
                        btn.style.opacity = '1';
                        btn.style.pointerEvents = 'auto';

                        // Remove hidden attribute if it exists
                        if (btn.hasAttribute('hidden')) {
                            btn.removeAttribute('hidden');
                        }
                    });

                    // Handle templates
                    const templates = container.querySelectorAll('template[is="dom-if"]');
                    if (templates.length > 0) {
                        console.log(`Found ${templates.length} templates in a container with "–" status`);
                    }
                } else {
                    // Reset if status is not "–"
                    container.classList.remove('show-buttons');
                }
            });
        }
    }

    // Initialize
    function init() {
        //console.log('YouTube Translation Buttons: Initializing smart mode');
        addCustomStyles();
    }

    // Utility function to debug status values
    function debugStatusValues() {
        const statuses = Array.from(document.querySelectorAll('#status-info')).map(el => el.textContent.trim());
        const uniqueStatuses = [...new Set(statuses)];
        console.log('Found status values:', uniqueStatuses);
        return uniqueStatuses;
    }

    // Make debug function available globally
    window.debugYTStatusValues = debugStatusValues;

    // 语言代码映射表
    const languageMapping = {
        "丹麦语": ["丹麦语"],
        "俄语": ["俄语"],
        "保加利亚语": ["保加利亚语"],
        "克罗地亚语": ["克罗地亚语"],
        "印地语": ["印地语"],
        "印度尼西亚语": ["印度尼西亚语"],
        "土耳其语": ["土耳其语"],
        "孟加拉语": ["孟加拉语"],
        "希伯来语": ["希伯来语"],
        "德语": ["德语"],
        "意大利语": ["意大利语"],
        "斯瓦希里语": ["斯瓦希里语"],
        "日语": ["日语"],
        "法语": ["法语"],
        "波斯语": ["波斯语"],
        "泰语": ["泰语"],
        "罗马尼亚语": ["罗马尼亚语"],
        "芬兰语": ["芬兰语"],
        "英语": ["英语"],
        "葡萄牙语": ["葡萄牙语"],
        "西班牙语": ["西班牙语"],
        "越南语": ["越南语"],
        "阿拉伯语": ["阿拉伯语"],
        "韩语": ["韩语"],
        "马来语": ["马来语"],
        "乌尔都语": ["乌尔都语"],
        "中文（繁体）": ["中文（繁体）"],
        "粤语（香港）": ["粤语（香港）"]
    };

    // 创建控制面板
    function createControlPanel() {
        const panel = document.createElement('div');
        Object.assign(panel.style, {
            position: 'fixed',
            top: '100px',
            right: '20px',
            zIndex: '9999',
            backgroundColor: 'white',
            padding: '10px',
            border: '1px solid #ccc',
            borderRadius: '5px',
            boxShadow: '0 2px 5px rgba(0,0,0,0.2)',
            display: 'flex',
            flexDirection: 'column',
            gap: '10px',
            width: '300px'
        });

        // 标题JSON输入框
        const jsonInputLabel = document.createElement('div');
        jsonInputLabel.textContent = '输入JSON格式的标题(格式:{\"语言\":\"标题\",...})';
        jsonInputLabel.style.marginTop = '10px';

        const jsonInput = document.createElement('textarea');
        Object.assign(jsonInput.style, {
            width: '100%',
            height: '100px',
            padding: '5px',
            boxSizing: 'border-box',
            marginBottom: '10px',
            fontFamily: 'monospace',
            fontSize: '12px'
        });
        jsonInput.id = 'title-json-input';
        jsonInput.placeholder = '{"英语": "The Little Squirrel\'s Jar", "西班牙语": "El frasco de la pequeña ardilla"}';

        // 一键添加语言并填充标题按钮
        const addAndFillButton = document.createElement('button');
        Object.assign(addAndFillButton.style, {
            padding: '10px',
            cursor: 'pointer',
            backgroundColor: '#065fd4',
            color: 'white',
            border: 'none',
            borderRadius: '3px',
            fontWeight: 'bold'
        });
        addAndFillButton.textContent = '一键添加语言并填充标题';
        addAndFillButton.onmouseover = () => addAndFillButton.style.backgroundColor = '#0356c2';
        addAndFillButton.onmouseout = () => addAndFillButton.style.backgroundColor = '#065fd4';
        addAndFillButton.onclick = addLanguagesWithTitles;

        // 添加状态显示区域
        const statusDiv = document.createElement('div');
        statusDiv.id = 'yt-lang-status';
        statusDiv.style.marginTop = '10px';
        statusDiv.style.fontSize = '12px';
        statusDiv.style.color = '#666';

        // 添加所有元素到面板
        panel.appendChild(jsonInputLabel);
        panel.appendChild(jsonInput);
        panel.appendChild(addAndFillButton);
        panel.appendChild(statusDiv);
        document.body.appendChild(panel);
    }

    // 更新状态显示
    function updateStatus(message, isError = false) {
        const statusDiv = document.getElementById('yt-lang-status');
        if (statusDiv) {
            statusDiv.textContent = message;
            statusDiv.style.color = isError ? 'red' : '#666';
        }
    }

    // 一键添加语言并填充标题的主函数
    async function addLanguagesWithTitles() {
        try {
            updateStatus('开始添加语言并填充标题...');
            console.log('开始添加语言并填充标题...');

            const jsonInput = document.getElementById('title-json-input');
            if (!jsonInput || !jsonInput.value.trim()) {
                throw new Error('请先输入JSON格式的标题数据');
            }

            // 解析JSON
            let titleData;
            try {
                titleData = JSON.parse(jsonInput.value.trim());
            } catch (e) {
                throw new Error('JSON格式错误，请检查格式');
            }

            // 处理每种语言
            for (const [lang, title] of Object.entries(titleData)) {
                console.log(`处理语言: ${lang}, 标题: ${title}`);
                updateStatus(`添加 ${lang} 并填充标题...`);

                // 点击添加按钮
                const addButton = await waitForElement(
                    'button',
                    button => button.textContent.includes('添加语言') ||
                             button.textContent.includes('Add language')
                );

                if (!addButton) {
                    throw new Error('找不到添加语言按钮');
                }

                console.log('找到添加按钮');
                addButton.click();
                await sleep(300);

                // 等待语言列表出现并选择语言
                const langOption = await waitForElement(
                    'tp-yt-paper-item',
                    item => {
                        const formattedString = item.querySelector('yt-formatted-string.item-text');
                        if (!formattedString) return false;
                        const text = formattedString.textContent.toLowerCase();
                        const possibleMatches = languageMapping[lang] || [lang];
                        return possibleMatches.some(match =>
                            text.startsWith(match.toLowerCase())
                        );
                    },
                    2000
                );

                if (!langOption) {
                    console.log(`找不到语言选项: ${lang}，跳过`);

                    // 点击取消按钮或点击外部区域关闭对话框
                    const cancelButton = document.querySelector('tp-yt-paper-button[dialog-dismiss]');
                    if (cancelButton) {
                        cancelButton.click();
                    } else {
                        // 尝试点击对话框外部
                        document.body.click();
                    }

                    await sleep(300);
                    continue;
                }

                console.log(`找到语言选项: ${lang}`);
                langOption.click();
                await sleep(300);

                // 等待并找到标题输入框 - 根据实际DOM结构定位
                await sleep(500); // 等待对话框完全加载

                // 首先尝试定位contenteditable div元素，这是YouTube使用的富文本输入
                let titleInput = await waitForElement(
                    '#metadata-title #textbox[contenteditable="true"], div[contenteditable="true"][aria-label*="标题"], div[contenteditable="true"][aria-label*="Title"]',
                    null,
                    2000
                );

                if (!titleInput) {
                    console.log(`尝试查找备用标题输入框...`);
                    // 备用方案：查找任何可能的标题输入
                    titleInput = await waitForElement(
                        'div[id="textbox"][contenteditable="true"], [aria-label*="标题"][contenteditable="true"]',
                        null,
                        2000
                    );
                }

                if (!titleInput) {
                    console.log(`找不到 ${lang} 的标题输入框，尝试最后的方案`);
                    // 最后的尝试 - 查找任何contenteditable元素
                    const editableDivs = document.querySelectorAll('div[contenteditable="true"]');
                    console.log(`找到 ${editableDivs.length} 个可编辑元素`);

                    // 检查是否有任何可编辑元素在容器中
                    const titleContainer = document.querySelector('#metadata-title-container, #metadata-title');
                    if (titleContainer) {
                        titleInput = titleContainer.querySelector('div[contenteditable="true"]');
                    }

                    if (!titleInput && editableDivs.length > 0) {
                        titleInput = editableDivs[0]; // 选择第一个可编辑div
                    }

                    if (!titleInput) {
                        console.log(`无法找到任何标题输入框，跳过`);
                        continue;
                    }
                }

                console.log(`找到标题输入框，填充标题: ${title}`);

                // 清空内容并填入新标题，使用安全的方法避免 TrustedHTML 错误

                // 方法 1: 使用 focus() 和 select all 然后替换
                titleInput.focus();
                // 全选当前内容
                document.execCommand('selectAll', false, null);
                // 删除选中内容
                document.execCommand('delete', false, null);
                // 插入新内容
                document.execCommand('insertText', false, title);

                // 触发输入事件以确保 YouTube 检测到变化
                titleInput.dispatchEvent(new Event('input', { bubbles: true }));
                titleInput.dispatchEvent(new Event('change', { bubbles: true }));

                // 记录操作结果
                console.log(`标题输入完成：${title}，当前内容：${titleInput.textContent}`);
                await sleep(300);

                // 查找更新按钮并点击
                await sleep(500); // 确保标题输入后有时间让更新按钮启用

                // 根据实际DOM结构定位更新按钮
                // 首先尝试使用类名和文本内容精确定位
                const updateButton = await waitForElement(
                    '.ytgn-language-dialog-update button, button.ytcp-button-shape-impl, ytcp-button.ytgn-language-dialog-update',
                    button => {
                        const text = button.textContent.trim().toLowerCase();
                        return text.includes('更新') ||
                               text.includes('update') ||
                               text.includes('保存') ||
                               text.includes('save');
                    },
                    2000
                );

                if (!updateButton) {
                    console.log(`找不到 ${lang} 的更新按钮，尝试查找备用按钮`);

                    // 备用方案1：查找对话框内的任何按钮
                    const dialogButtons = document.querySelectorAll('tp-yt-paper-dialog button, #dialog button');
                    const updateBtn = Array.from(dialogButtons).find(button => {
                        const text = button.textContent.trim().toLowerCase();
                        return text.includes('更新') ||
                               text.includes('update') ||
                               text.includes('保存') ||
                               text.includes('save');
                    });

                    if (updateBtn) {
                        console.log('找到备用更新按钮');
                        updateBtn.click();
                    } else {
                        // 备用方案2：查找ytcp-button元素
                        const buttons = document.querySelectorAll('ytcp-button');
                        for (const btn of buttons) {
                            const buttonText = btn.textContent.trim().toLowerCase();
                            if (buttonText.includes('更新') || buttonText.includes('update')) {
                                console.log('找到ytcp-button更新按钮');
                                // 尝试移除disabled属性
                                const buttonElement = btn.querySelector('button');
                                if (buttonElement && buttonElement.hasAttribute('disabled')) {
                                    buttonElement.removeAttribute('disabled');
                                }
                                // 点击button而不是ytcp-button
                                if (buttonElement) {
                                    buttonElement.click();
                                } else {
                                    btn.click();
                                }
                                break;
                            }
                        }
                    }
                } else {
                    console.log('找到更新按钮，点击更新');

                    // 检查按钮是否被禁用，并等待它变为启用状态
                    if (updateButton.hasAttribute('disabled') || updateButton.classList.contains('ytcp-button-shape-impl--disabled') ||
                        updateButton.parentElement.hasAttribute('disabled') || updateButton.getAttribute('aria-disabled') === 'true') {
                        console.log('更新按钮被禁用，等待启用...');

                        // 等待短暂时间，让按钮可能变为启用状态
                        await sleep(2000);

                        // 再次检查按钮状态
                        if (updateButton.hasAttribute('disabled') || updateButton.getAttribute('aria-disabled') === 'true') {
                            console.log('更新按钮仍被禁用，尝试模拟标题修改事件再次触发验证...');

                            // 再次触发标题输入事件，可能会启用更新按钮
                            if (titleInput) {
                                titleInput.dispatchEvent(new Event('input', { bubbles: true }));
                                titleInput.dispatchEvent(new Event('change', { bubbles: true }));
                                titleInput.dispatchEvent(new Event('blur', { bubbles: true }));
                                await sleep(1000);
                            }
                        }
                    }

                    // 尝试使用各种方法触发按钮点击
                    try {
                        console.log('尝试点击更新按钮...');
                        updateButton.click();

                        // 额外的点击尝试
                        await sleep(500);
                        if (!updateButton.disabled) {
                            // 如果直接点击不起作用，尝试创建和分发点击事件
                            const clickEvent = new MouseEvent('click', {
                                bubbles: true,
                                cancelable: true,
                                view: window
                            });
                            updateButton.dispatchEvent(clickEvent);

                            // 如果是复合组件，尝试找到里面的真正按钮元素
                            const innerButton = updateButton.querySelector('button');
                            if (innerButton) {
                                console.log('尝试点击内部按钮');
                                innerButton.click();
                                innerButton.dispatchEvent(clickEvent);
                            }

                            // 检查是否有父级 ytcp-button 元素
                            const parentButton = updateButton.closest('ytcp-button');
                            if (parentButton && parentButton !== updateButton) {
                                console.log('尝试点击父级按钮');
                                parentButton.click();
                            }
                        }
                    } catch (e) {
                        console.error('点击更新按钮时出错:', e);
                    }
                }

                await sleep(1000); // 等待保存完成
            }

            updateStatus('所有语言和标题添加完成！');
            alert('所有语言和标题添加完成！');
        } catch (error) {
            console.error('添加语言并填充标题出错：', error);
            updateStatus(`操作失败：${error.message}`, true);
            alert(`添加语言并填充标题失败：${error.message}\n请打开控制台查看详细信息`);
        }
    }

    // 工具函数：等待元素出现（带条件判断）
    async function waitForElement(selector, condition = null, timeout = 5000) {
        const startTime = Date.now();

        while (Date.now() - startTime < timeout) {
            const elements = Array.from(document.querySelectorAll(selector));

            if (condition) {
                const element = elements.find(condition);
                if (element) return element;
            } else {
                if (elements.length > 0) return elements[0];
            }

            await sleep(100);
        }

        return null;
    }

    // 工具函数：延迟
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // 等待页面加载完成后再创建控制面板
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            createControlPanel();
            init();
        });
    } else {
        createControlPanel();
        init();
    }
})();